import 'package:distribution_mall_flutter/Introduction/Introduction_hone_one.dart';
import 'package:distribution_mall_flutter/Introduction/Introduction_hone_two.dart';
import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/entity/goods/list/goods_list_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/tab.dart';
import 'package:distribution_mall_flutter/provider/home/waterfall.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/overlay_manager.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:distribution_mall_flutter/widgets/earn.dart';
import 'package:distribution_mall_flutter/widgets/ink_well_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:skeletonizer/skeletonizer.dart';

class EPGoodsItemCard extends ConsumerStatefulWidget {
  final Item data;
  final String tag;
  final int index;

  const EPGoodsItemCard(
      {super.key, required this.data, required this.index, required this.tag});

  @override
  ConsumerState<EPGoodsItemCard> createState() => _EPGoodsItemCardState();
}

class _EPGoodsItemCardState extends ConsumerState<EPGoodsItemCard> {
  GlobalKey? _key;
  GlobalKey? _titleKey;
  GlobalKey? _lockKey;
  GlobalKey? _subTitleKey;
  GlobalKey? _msrpKey;
  GlobalKey? _kitaKey;

  ///引导第几步
  int guideStep = 0;

  ///是否展示引导页
  ///判断saleUnitId不是test,如果是test就说明网络请求没有加载出来,等待网络出来后就没问题了
  bool get needShowGuideDialog =>
      widget.index == 0 &&
      EPstorage.guide
          .get(GuideBoxKey.homeProductItemGuide, defaultValue: true) &&
      !widget.data.saleUnitId!.startsWith('test');

  // bool get needShowGuideDialog => false;

  @override
  void initState() {
    super.initState();
    if (needShowGuideDialog) {
      _key = GlobalKey();
      _titleKey = GlobalKey();
      _lockKey = GlobalKey();
      _subTitleKey = GlobalKey();
      _msrpKey = GlobalKey();
      _kitaKey = GlobalKey();
    }
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      showGuideDialog();
    });
  }

  Item generateItemData() {
    var data = widget.data;

    ///如果是准备弹出引导页的那么暂时返回模拟数据(按照设计图)
    if (needShowGuideDialog) {
      return data.copyWith(
        priceInfo: data.priceInfo
            ?.copyWith(maxProfitPrice: 100, maxSuggestedRetailPrice: 500.00),
        brandInfo: data.brandInfo?.copyWith(brandName: 'TJOY'),
        categoryInfo: data.categoryInfo?.copyWith(categoryName: 'face cream'),
      );
    } else {
      return data;
    }
  }

  showGuideDialog() {
    if (_key == null || ref.read(loginStateProvider)) {
      return;
    }
    if (!mounted) {
      return;
    }
    if (tabName.indexOf(widget.tag) != 0) {
      return;
    }
    OverlayEntry? lastOverlay;
    lastOverlay = OverlayEntry(builder: (ctx) {
      return GestureDetector(
          onTap: () {
            ref.read(overlayManagerProvider.notifier).close(lastOverlay);
            setState(() {
              guideStep = 1;
            });
          },
          behavior: HitTestBehavior.opaque,
          child: IntroductionHoneOne(
            content: buildBottom(
                itemData: generateItemData(),
                isGuideOne: true,
                isGuideTwo: false,
                isLogin: false),
            data: generateItemData(),
            contentInfo: WidgetLocationInfo.fromKey(_key)!,
            titleInfo: WidgetLocationInfo.fromKey(_titleKey)!,
            subTitleInfo: WidgetLocationInfo.fromKey(_subTitleKey)!,
            lockInfo: WidgetLocationInfo.fromKey(_lockKey),
          ));
    });
    ref.read(overlayManagerProvider.notifier).insert(lastOverlay,
        closeListener: () {
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        await Future.delayed(const Duration(milliseconds: 30));
        lastOverlay = OverlayEntry(builder: (ctx) {
          return GestureDetector(
              onTap: () async {
                ref.read(overlayManagerProvider.notifier).close(lastOverlay);
                setState(() {});
              },
              behavior: HitTestBehavior.opaque,
              child: IntroductionHoneTwo(
                content: buildBottom(
                    itemData: generateItemData(),
                    isGuideOne: false,
                    isGuideTwo: true,
                    isLogin: false),
                data: widget.data,
                contentInfo: WidgetLocationInfo.fromKey(_key)!,
                msrpInfo: WidgetLocationInfo.fromKey(_msrpKey),
                kitaInfo: WidgetLocationInfo.fromKey(_kitaKey),
                goLogin: () async {
                  lastOverlay?.remove();
                  await EPstorage.guide
                      .put(GuideBoxKey.homeProductItemGuide, false);
                  setState(() {});
                  appRouter.push(const LoginRoute());
                },
              ));
        });
        ref.read(overlayManagerProvider.notifier).insert(lastOverlay!,
            closeListener: () {
          EPstorage.guide.put(GuideBoxKey.homeProductItemGuide, false);
        });
      });
    });
  }

  final TextStyle miniPrice = const TextStyle(
    fontSize: 10.9,
    color: Color.fromRGBO(216, 216, 216, 1),
    letterSpacing: TextConstant.letterSpacing,
  );
  final TextStyle price = const TextStyle(
    fontSize: 16.4,
    fontWeight: FontWeight.bold,
    color: Colors.black,
    letterSpacing: TextConstant.letterSpacing,
  );

  @override
  Widget build(BuildContext context) {
    bool bol = ref.watch(loginStateProvider);
    var itemData = generateItemData();
    return EPInkWellView(
        width: double.infinity,
        borderRadius: const BorderRadius.all(Radius.circular(14.6)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                AspectRatio(
                    aspectRatio: 1,
                    child: ImageLoader.imageNet(
                        itemData.imageInfo?.imageUrl ?? '',
                        isReplace: true,
                        radius: 14.6,
                        fit: BoxFit.cover)),
                if (itemData.sample == true)
                  Positioned(
                    right: 7,
                    top: 6,
                    child: Image.asset(
                      Assets.assets_icons_free_sample_png,
                      height: 20,
                    ),
                  ),
              ],
            ),
            buildBottom(
              itemData: itemData,
              isGuideOne: needShowGuideDialog && guideStep == 0,
              isGuideTwo: needShowGuideDialog && guideStep == 1,
              isLogin: bol,
              contentKey: _key,
              titleKey: _titleKey,
              subTitleKey: _subTitleKey,
              lockKey: _lockKey,
              msrpKey: _msrpKey,
              kitaKey: _kitaKey,
            ),
          ],
        ),
        onPressed: () {
          // showGuideDialog();
          // return;
          FirebaseAnalyticsUtils.logEvent(
              name: PointConstant.hpProduct,
              parameters: {
                'saleItemId': itemData.refSaleItemId,
                'tag': widget.tag
              });
          // appRouter
          //     .pushNamed('/productDetails/${itemData.refSaleItemId ?? ''}');
          appRouter.push(
              ProductDetailsRoute(saleItemId: itemData.refSaleItemId ?? ''));
        });
  }

  ///引导页整体布局还是复用用这个,只是有些不同
  Container buildBottom({
    required Item itemData,
    required bool isGuideOne,
    required bool isGuideTwo,
    required bool isLogin,
    Key? contentKey,
    Key? titleKey,
    Key? subTitleKey,
    Key? lockKey,
    Key? msrpKey,
    Key? kitaKey,
  }) {
    return Container(
      key: contentKey,
      padding: const EdgeInsets.symmetric(horizontal: 3),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(

              ///由于小锁有距离,写成5吧
              padding: const EdgeInsets.only(top: 5, bottom: 8),
              child: Wrap(
                runAlignment: WrapAlignment.end,
                crossAxisAlignment: WrapCrossAlignment.end,
                children: [
                  Container(
                    padding: const EdgeInsets.only(
                      right: 10,
                    ),
                    constraints: const BoxConstraints(maxWidth: 160),
                    child: Text(
                      key: titleKey,
                      itemData.brandInfo?.brandName ?? '',
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      style: const TextStyle(
                          letterSpacing: TextConstant.letterSpacing,
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                          color: Color.fromRGBO(23, 23, 23, 1)),
                    ),
                  ),
                  // ConstrainedBox(
                  //   constraints: const BoxConstraints(maxWidth: 70),
                  //   child: Text(
                  //     data?.brandInfo?.brandName ?? '',
                  //     overflow: TextOverflow.ellipsis,
                  //     maxLines: 2,
                  //     style: const TextStyle(
                  //         letterSpacing: TextConstant.letterSpacing,
                  //         fontWeight: FontWeight.bold,
                  //         fontSize: FontConstant.f127,
                  //         color: Color.fromRGBO(23, 23, 23, 1)),
                  //   ),
                  // ),
                  if (itemData.categoryInfo?.categoryName != null)
                    Skeleton.leaf(
                        child: Container(
                      key: subTitleKey,
                      constraints: BoxConstraints(
                          maxWidth:
                              (MediaQuery.of(context).size.width - 6) / 2),
                      margin: const EdgeInsets.only(top: 3),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 3.6, vertical: 0),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(3.6),
                        color: const Color.fromRGBO(245, 246, 248, 1),
                      ),
                      child: Text(itemData.categoryInfo?.categoryName ?? '',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            letterSpacing: TextConstant.letterSpacing,
                            fontSize: FontConstant.f127,
                            color: Color.fromRGBO(119, 119, 119, 1),
                          )),
                    ))
                ],
              )),
          Container(
            margin: const EdgeInsets.only(bottom: 8),
            child: Row(
              children: [
                isLogin
                    ? Row(
                        children: [
                          Visibility(
                              visible: itemData.priceInfo?.minSalePrice != null,
                              child: Container(
                                  constraints:
                                      const BoxConstraints(maxWidth: 80),
                                  child: Utils.currencyWidget(
                                      Utils.formatDouble(
                                          itemData.priceInfo?.minSalePrice),
                                      mainAxisSize: MainAxisSize.min,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      symbolStyle: const TextStyle(
                                          fontWeight: FontWeight.w500,
                                          fontSize: 9,
                                          color: Colors.black),
                                      priceStyle: const TextStyle(
                                          fontWeight: FontWeight.w600,
                                          fontSize: 18,
                                          color: Colors.black)))),

                          ///如果是第二步引导页不登录也要展示这个
                          if (isGuideTwo ||
                              (isLogin &&
                                  itemData.priceInfo?.maxProfitPrice != null &&
                                  (itemData.priceInfo?.maxProfitPrice ?? 0) >
                                      0))
                            buildMaxProfitPrice(kitaKey, itemData),
                        ],
                      )
                    : Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          if (!isGuideTwo)
                            Row(
                              children: [
                                Text(
                                  S.current.productDetails_unlock,
                                  style: const TextStyle(
                                      color: Color.fromRGBO(84, 131, 191, 1),
                                      fontSize: FontConstant.f127,
                                      letterSpacing:
                                          TextConstant.letterSpacing),
                                ),
                                const SizedBox(
                                  width: 3,
                                ),
                                ImageLoader.imageAsset(ImageLocalConstant.lock,
                                    width: 14.6, height: 14.6, key: lockKey)
                              ],
                            ),
                          Row(
                            children: [
                              ///如果是第二步引导页不登录也要展示这个
                              if (isGuideTwo) ...[
                                Visibility(
                                    visible: itemData.priceInfo?.minSalePrice !=
                                        null,
                                    child: Container(
                                        constraints:
                                            const BoxConstraints(maxWidth: 80),
                                        child: Utils.currencyWidget(
                                            Utils.formatDouble(itemData
                                                .priceInfo?.minSalePrice),
                                            mainAxisSize: MainAxisSize.min,
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            symbolStyle: const TextStyle(
                                                fontWeight: FontWeight.w500,
                                                fontSize: 9,
                                                color: Colors.black),
                                            priceStyle: const TextStyle(
                                                fontWeight: FontWeight.w600,
                                                fontSize: 18,
                                                color: Colors.black)))),
                              ],

                              ///如果是第二步引导页不登录也要展示这个
                              if (isGuideTwo ||
                                  (isLogin &&
                                      itemData.priceInfo?.maxProfitPrice !=
                                          null &&
                                      (itemData.priceInfo?.maxProfitPrice ??
                                              0) >
                                          0))
                                buildMaxProfitPrice(kitaKey, itemData),
                            ],
                          ),
                        ],
                      ),
              ],
            ),
          ),
          Visibility(
              visible: itemData.priceInfo?.maxSuggestedRetailPrice != null,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    key: msrpKey,
                    '${S.current.msrp} : ',
                    style:
                        const TextStyle(fontSize: 14, color: Color(0xFF9E9E9E)),
                  ),
                  Expanded(
                    child: Text(
                        '₱${Utils.formatDouble(itemData.priceInfo?.maxSuggestedRetailPrice)}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                            fontSize: 14, color: Color(0xFF9E9E9E))),
                  )
                ],
              )),
        ],
      ),
    );
  }

  Widget buildMaxProfitPrice(Key? kitaKey, Item itemData) {
    return Container(
      margin: const EdgeInsets.only(left: 4),
      child: Row(
        children: [
          // ImageLoader.imageNet(
          //   ImageConstant.homeGoodItemArrowLeft,
          //   isReplace: false,
          //   height: 10,
          // ),
          Image.asset(
            Assets.assets_icons_home_good_item_arrow_left_png,
            height: 10,
          ),
          EPEarn(
              key: kitaKey,
              marginTop: 0,
              text:
                  Utils.formatDouble(itemData.priceInfo?.maxProfitPrice ?? 0)),
        ],
      ),
    );
  }
}
